package com.diary.server.controller;

import com.diary.common.result.Result;
import com.diary.server.dto.UploadDTO;
import com.diary.server.service.impl.aliOssServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.net.MalformedURLException;
import java.net.URL;

@RestController
@Slf4j
@RequestMapping("/upload")
@Tag(name = "上传接口")
public class OssController {

    public static String modifyOssUrl(String originalUrl) throws MalformedURLException {
        if (originalUrl == null || originalUrl.isEmpty()) {
            return originalUrl;
        }

        try {
            URL url = new URL(originalUrl);
            String protocol = url.getProtocol(); // https
            String hostname = url.getHost();     // oss-cn-shanghai.aliyuncs.com
            String path = url.getPath();         // /oss/upload/...
            String query = url.getQuery();       // 查询参数（如果有）
            int port = url.getPort();            // 端口号（如果有）

            // 在hostname前添加ttdiary.
            String newHostname = "ttdiary." + hostname;

            // 构造新的URL
            StringBuilder newUrl = new StringBuilder();
            newUrl.append(protocol).append("://").append(newHostname);

            // 如果有端口号则添加
            if (port != -1) {
                newUrl.append(":").append(port);
            }

            // 添加路径
            newUrl.append(path);

            // 如果有查询参数则添加
            if (query != null && !query.isEmpty()) {
                newUrl.append("?").append(query);
            }

            return newUrl.toString();
        } catch (MalformedURLException e) {
            throw new MalformedURLException("Invalid URL format: " + originalUrl);
        }
    }

    @Autowired
    private aliOssServiceImpl aliOssService;

    @PostMapping(consumes = {
            "multipart/form-data",
            "multipart/form-data;charset=UTF-8"
    })
    @Operation(summary = "上传文件")
    public Result<String> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "name", required = false) String name) {

        try {
            // 如果没有提供name参数，可以从文件中获取原始文件名
            String fileName = name;
            if (fileName == null || fileName.isEmpty()) {
                fileName = file.getOriginalFilename();
            }

            String url = aliOssService.uploadImage(fileName, file);
            if (url != null) {
                return Result.success(modifyOssUrl(url));
            } else {
                return Result.error("上传失败");
            }
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("上传失败: " + e.getMessage());
        }
    }

    // 如果你仍然需要支持JSON格式的上传（通过其他方式），可以添加另一个方法
    @PostMapping(consumes = "application/json")
    @Operation(summary = "通过JSON上传（备用）")
    public Result<String> uploadJson(@RequestBody UploadDTO uploadDTO) {
        try {
            String url = aliOssService.uploadImage(uploadDTO.getName(), uploadDTO.getFile());
            if (url != null) {
                return Result.success(url);
            } else {
                return Result.error("上传失败");
            }
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return Result.error("上传失败: " + e.getMessage());
        }
    }
}
